<template>
	<comp-navbar :title="title" bgColor="#fff" :fixed="true" :z-index="999999"></comp-navbar>
	<up-form ref="form" :model="formstate" :rules="rules" :labelWidth="90">
		<view class="add_wrap">
			<view class="form_wrap">
				<view class="title">客户登记（必填）</view>
				<up-form-item label="客户姓名" prop="name">
					<up-input v-model="formstate.name" placeholder="请填写客户姓名"></up-input>
				</up-form-item>
				<up-form-item label="客户手机号" prop="phone">
					<up-input v-model="formstate.phone" placeholder="请填写客户手机号" type="number"></up-input>
				</up-form-item>
			</view>
			<view class="form_wrap">
				<view class="title">仪式信息（必填）</view>
				<up-form-item label="仪式名称" prop="ysname">
					<up-input v-model="formstate.ysname" placeholder="请填写仪式名称"></up-input>
				</up-form-item>
				<up-form-item label="所属展厅" prop="yszt" class="form_item">
					<view class="pick_select flex" @click="handlezt">
						<view class="pick_text">{{ztvalue}}</view>
						<view class="iconfont icon-youjiantou"></view>
					</view>
					<comp-picker :show="ztshow" :columns="ztcolumns" @cancel="ztshow=false" @confirm="handlezt_confirm"
						keyName="label" :defaultIndex="[ztindex]"></comp-picker>
				</up-form-item>
				<up-form-item label="仪式类型" prop="ystype" class="form_item">
					<view class="pick_select flex" @click="handleys">
						<view class="pick_text">{{ysvalue}}</view>
						<view class="iconfont icon-youjiantou"></view>
					</view>
					<comp-picker :show="ysshow" :columns="yscolumns" @cancel="ysshow=false" @confirm="handleys_confirm"
						keyName="label" :defaultIndex="[ysindex]"></comp-picker>
				</up-form-item>
				<up-form-item label="仪式开始日期" prop="ysdate" class="form_item">
					<view class="flex">
						<view class="flex com_date">
							<up-datetime-picker hasInput :show="dateshow" v-model="datevalue" mode="date"
								:minDate="mindate" @confirm="datetimeconfirm"></up-datetime-picker>
							<view class="iconfont icon-ico_yuyueguanli_jiedaiyuyue"></view>
						</view>
						<view class="flex com_date">
							<up-datetime-picker hasInput :show="timeshow_l" v-model="timevalue"
								mode="time"></up-datetime-picker>
							<view class="iconfont icon-shijian"></view>
						</view>
						<view class="flex com_date">
							<up-datetime-picker hasInput :show="timeshow_r" v-model="timevalue2"
								mode="time"></up-datetime-picker>
							<view class="iconfont icon-shijian"></view>
						</view>
					</view>
				</up-form-item>
				<up-form-item label="大屏互动" prop="interactive" class="form_item">
					<up-switch v-model="interactive"></up-switch>
				</up-form-item>

			</view>
			<view class="form_wrap">
				<view class="title">逝者信息（选填）</view>
				<view class="tab_wrap flex">
					<view class="tab_btn" :class="[tabIndex == 0 ? 'tab_act': '']" @click="handleTab(0)">
						手动添加</view>
					<!-- <view class="tab_btn" :class="[tabIndex == 1 ? 'tab_act': '']" @click="handleTab(1)">墓穴查询</view> -->
				</view>
				<view class="deceased">
					<template v-if="aloneList.length">
						<view class="deceased_item flex" v-for="(item,index) in aloneList" :key="index">
							<up-checkbox :customStyle="{marginBottom: '8px'}" label="" name="agree" usedAlone
								v-model:checked="item.check">
							</up-checkbox>
							<img :src="baseUrl + '/' + item.imgUrl" class="img" />
							<view class="deceased_label">
								<view class="label_t">
									{{item.name}}
								</view>
								<view class="label_b">
									{{item.sexname}}
								</view>
							</view>
							<view class="deceased_btn_wrap flex">
								<view class="deceased_btn edit" @click="relOpen(item)">
									编辑
								</view>
								<view class="deceased_btn del" @click="reldelte(item.ID)">
									删除
								</view>
							</view>
						</view>
					</template>
					<view class="no-data" v-else>暂无逝者信息</view>
				</view>
			</view>
			<up-button class="savebtn" @click="handlesave" text="提交"></up-button>
		</view>
	</up-form>

	<!-- 填写逝者信息弹窗 -->
	<up-popup :show="relShow" @close="relClose" mode="center" overlayOpacity="0.8" bgColor="transparent"
		:overlayStyle="{backdropFilter:'blur(10px)'}">
		<RelInfoComp :config="relConfig" :data="editAlone" />
	</up-popup>

	<!-- 删除二次确认 -->
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		unref
	} from 'vue';

	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		request,
		baseUrl
	} from '@/utils/request.js'
	import dayjs from 'dayjs';
	import RelInfoComp from './relinfo.vue'

	const title = ref('创建仪式')
	const editType = ref(false)
	const szflag = ref(false) // 判断逝者额关系
	const yiid = ref('')

	const form = ref(null);
	const formstate = ref({
		name: '',
		phone: '',
		ysname: '',
	})
	const rules = {
		name: [{
			required: true,
			message: '请输入客户姓名',
			trigger: ['blur', 'change'],
		}],
		phone: [{
			required: true,
			message: '请输入客户手机号',
			trigger: ['blur', 'change'],
		}],
		ysname: [{
			required: true,
			message: '请输入仪式名称',
			trigger: ['blur', 'change'],
		}],
	}



	//获取编辑的信息

	const detailInfo = ref({})
	const deceasedInfo = ref([])
	const getDetail = async (data) => {
		const res = await request({
			url: '/SZ_CeremonyOrders/GetCeremonyOrdersListID',
			method: 'GET',
			data
		})
		const detailInfo = res.Data[0]
		const deceaseddata = res.DataTwo
		formstate.value.name = detailInfo.CustomerName
		formstate.value.phone = detailInfo.CustomerPhone
		formstate.value.ysname = detailInfo.Ceremonytheme
		//ysvalue.value = detailInfo.label;
		yskey.value = detailInfo.CeremonyType;
		ysvalue.value = yscolumns.value[0].filter(v => v.id == detailInfo.CeremonyType)[0]?.label

		ztvalue.value = detailInfo.ExhibitionhallName
		ztkey.value = detailInfo.ChannelExhibitionHallID;
		interactive.value = detailInfo.largescreenHD == 1 ? false : true;
		const endtimeres = detailInfo.EndTime.split(' ')
		const stimeres = detailInfo.StartTime.split(' ')
		datevalue.value = endtimeres[0]
		timevalue.value = stimeres[1]
		timevalue2.value = endtimeres[1]
		console.log('deceaseddata--', deceaseddata)
		// 逝者信息
		aloneList.value = deceaseddata?.map(v => {
			return {
				...v,
				name: v.Name,
				imgUrl: v.ImgUrl,
				check: true,
				sex: v.Sex,
				sexname: v.Sex == 0 ? '男' : '女'
			}
		})
		uni.setStorageSync('funeralinfo', aloneList.value)
		detailInfo.value = res.Data[0];
		deceasedInfo.value = res.DataTwo
		szflag.value = deceaseddata.length > 0 ? true : false;

	}

	onLoad(async (opt) => {
		const {
			type,
			id
		} = opt;
		await getdownAllList()
		if (type == 1) {
			title.value = '编辑仪式'
			editType.value = true
			getDetail({
				ID: id
			})
			yiid.value = id
		} else {
			title.value = '创建仪式'
			editType.value = false
		}
		getAllszInfo()
	})

	onUnload(() => {
		console.log('onUnload....')
		// 删除换成的逝者信息
		uni.removeStorageSync('funeralinfo')
	})


	// 展厅
	const ztshow = ref(false);
	const ztcolumns = ref([]);
	const ztvalue = ref('') // ztcolumns.value[0][0].label 
	const ztindex = ref(0)
	const ztkey = ref(-1)
	const handlezt = () => {
		ztshow.value = true
	}
	const handlezt_confirm = ({
		index,
		value
	}) => {
		ztshow.value = false
		//console.log('pp', index, value)
		ztindex.value = index;
		ztvalue.value = value[0].label
		ztkey.value = value[0].id;
	}
	// 仪式类型
	const ysshow = ref(false);
	// [
	// 	[{
	// 		label: '追思',
	// 		id: 1
	// 	}, {
	// 		label: '祭拜',
	// 		id: 2
	// 	}, {
	// 		label: '思念',
	// 		id: 3
	// 	}]
	// ]
	const yscolumns = ref([]);
	const ysvalue = ref('')
	const yskey = ref(-1)
	const ysindex = ref(0)
	const handleys = () => {
		ysshow.value = true
	}
	const handleys_confirm = ({
		index,
		value
	}) => {
		ysshow.value = false
		ysindex.value = index;
		ysvalue.value = value[0].label;
		yskey.value = value[0].id;
		console.log('confirm', yskey.value)
	}


	// 获取所有展厅
	const getdownAllList = async () => {
		const res = await request({
			url: '/SZ_CeremonyOrders/GetDropdownlist',
			method: 'GET'
		})
		if (!res.Status) return

		const ztdata = res?.Data?.map(v => {
			return {
				label: v.value,
				id: v.key
			}
		})
		const ysdata = res?.DataTwo?.map(v => {
			return {
				label: v.value,
				id: v.key
			}
		})
		ztcolumns.value = [ztdata]
		yscolumns.value = [ysdata]
		if (!editType.value) {
			ysvalue.value = ysdata[0].label;
			yskey.value = ysdata[0].id;
			ztkey.value = ztdata[0].id;
			ztvalue.value = ztdata[0].label;
		}

	}
	// 日期
	const timeFormat = uni.$u.timeFormat;
	const dateshow = ref(false)
	const datevalue = ref(timeFormat(Date.now(), 'yyyy-mm-dd'))
	const mindate = ref(Date.now())
	const timeshow_l = ref(false)
	const timeshow_r = ref(false)
	const timevalue = ref('00:00')
	const timevalue2 = ref('23:59')

	const datetimeconfirm = (e, type) => {

		const {
			value,
			mode
		} = e;

		//console.log('date', e, timeFormat(value))
		if (mode == 'date') {
			datevalue.value = timeFormat(value, 'yyyy-mm-dd')
		}
	}

	// 大屏互动
	const interactive = ref(true)

	// 逝者信息
	const editAlone = ref({})
	const aloneList = ref([])
	const tabIndex = ref(-1);
	const handleTab = (num) => {
		if (num == 0) {
			addrelOpen()
		}
		tabIndex.value = num;
	}



	//获取所有逝者信息
	const getAllszInfo = async () => {
		// 新增获取
		const funeralinfo = uni.getStorageSync('funeralinfo')
		console.log('初始化逝者..', funeralinfo)
		if (!funeralinfo) return;
		aloneList.value = funeralinfo?.map(v => {

			return {
				...v,
				//imgUrl: editType.value ? v.imgUrl : baseUrl + '/' + v.imgUrl,
				check: true
			}
		})

	}

	// 逝者信息新增保存
	const savealoneAjax = async (data) => {

		const res = await request({
			url: '/SZ_FuneralCompanyTheDeceased/AddFuneralCompanyTheDeceased',
			data,
		})
		return res;
	}

	const saveaeditloneAjax = async (data) => {

		const res = await request({
			url: '/SZ_FuneralCompanyTheDeceased/UpdateFuneralCompanyTheDeceased',
			data,
		})
		return res;
	}

	// 提交
	const handlesave = (e) => {

		form.value.validate()?.then(async res => {
			//console.log('aloneList.value', aloneList.value)
			//return;
			if (res) {
				// console.log('参数...', formstate.value, ztvalue.value, ysvalue.value, datevalue.value,
				// 	timevalue.value, timevalue2.value)
				const lyparams = {
					customerName: formstate.value.name,
					customerPhone: formstate.value.phone,
					ceremonyType: yskey.value,
					ceremonytheme: formstate.value.ysname,
					channelExhibitionHallID: ztkey.value,
					startTime: `${datevalue.value} ${timevalue.value}`,
					endTime: `${datevalue.value} ${timevalue2.value}`,
					duration: 0,
					largescreenHD: Number(interactive.value), // 大屏互动0开启1关闭
					interactiveMode: 0,
					tosacrifice: 0,
				}
				// 比较时间大小
				const stime = dayjs(lyparams.startTime)
				const etime = dayjs(lyparams.endTime)
				if (etime.isBefore(stime)) {
					uni.$u.toast('仪式日期开始时间不能早于结束时间')
					return
				}
				let res
				if (editType.value) {
					lyparams.ceremonyOrdersID = yiid.value
					res = await request({
						url: '/SZ_CeremonyOrders/UpdateCeremonyOrders',
						data: lyparams,
					})
				} else {
					res = await request({
						url: '/SZ_CeremonyOrders/AddCeremonyOrders',
						data: lyparams,
					})
				}

				console.log('yshiid', res)
				// 保存逝者信息
				// const res_two = await request({
				// 	url: '/SZ_FuneralCompanyTheDeceased/AddFuneralCompanyTheDeceased',
				// 	data,
				// })
				let num = 0
				const alonedata = aloneList.value.filter(v => v.check)
				console.log('alonedata--', alonedata)
				if (!alonedata.length) {
					uni.$u.toast('保存成功')
					uni.switchTab({
						url: '/pages/yishi/yishi'
					})
					return
				}
				for (let i = 0; i < alonedata.length; i++) {
					const data = {
						name: alonedata[i].name,
						sex: alonedata[i].sex,
						imgUrl: alonedata[i].imgUrl,
						ceremonyOrdersID: yiid.value || res.Data
					}
					console.log('data', data)
					let result
					if (szflag.value) {
						//const editId = alonedata.filter(v => v.ID)[0]
						const id = alonedata[i].ID
						if (id) {
							data.id = id;
							result = await saveaeditloneAjax(data);
						} else {
							result = await savealoneAjax(data);
						}

					} else {
						result = await savealoneAjax(data);
					}
					num++;
					if (num >= alonedata.length) {
						uni.$u.toast('保存成功');
						uni.switchTab({
							url: '/pages/yishi/yishi'
						})
						return
					}
				}

			} else {
				uni.$u.toast('您还有信息未填写完成，请继续填写')
			}
		}).catch(errors => {
			console.log(errors)
			uni.$u.toast('您还有信息未填写完成，请继续填写')
		})
	}

	// 逝者信息弹窗

	const relShow = ref(false);
	const relClose = () => {
		relShow.value = false
		console.log('00000')
	};

	const addrelOpen = () => {
		relShow.value = true;
		editAlone.value = {}
		uni.removeStorageSync('editalone')
	}


	const relOpen = (res) => {

		const editAlones = unref(aloneList.value).filter(v => v.ID == res.ID)[0]
		editAlone.value = editAlones;
		//uni.setStorageSync('editalone', editAlones)

		relShow.value = true

	}

	const delajax = async (id) => {
		// /api/SZ_FuneralCompanyTheDeceased/DelFuneralCompanyTheDeceased
		const res = await request({
			url: '/SZ_FuneralCompanyTheDeceased/DelFuneralCompanyTheDeceased',
			data: {
				id
			},
			method: 'GET'
		})
	}

	// 删除逝者
	const reldelte = (id) => {
		//if(editType)

		const funeralinfo = uni.getStorageSync('funeralinfo')
		if (!funeralinfo) return;

		aloneList.value = funeralinfo.filter(v => v.ID != id).map(v => {
			return {
				...v,
				check: editType.value ? true : false
			}
		})
		uni.setStorageSync('funeralinfo', aloneList.value)
		if (id) {
			delajax(id)
		}

	}

	const relConfig = {
		relClose,
		getAllszInfo,
		editType,
		editAlone
	}
	onMounted(() => {
		//getdownAllList()
		//getAllszInfo()
	})
</script>

<style lang="scss">
	.add_wrap {

		padding: 120rpx 20rpx 20rpx 20rpx;

		.form_wrap {
			font-size: 28rpx;

			.title {
				margin-bottom: 20rpx;
				font-weight: bold;
				text-align: center;
			}

			.form_item {
				margin-bottom: 20rpx;

				.form_l {
					// color: ;
					width: 160rpx;
				}

				.com_input {
					flex: 1;
					padding-left: 20rpx;
					height: 60rpx;
					line-height: 60rpx;
					border: 1rpx solid $bor-color;
					box-sizing: border-box;
					border-radius: 6rpx;
				}

				.pick_select {
					flex: 1;
					justify-content: space-between;
					padding-left: 20rpx;
					height: 60rpx;
					line-height: 60rpx;
					border: 1rpx solid $bor-color;
					box-sizing: border-box;
					border-radius: 6rpx;
				}

				.com_date {
					margin-left: 10rpx;
					padding-right: 2rpx;
					border: 1rpx solid $bor-color;
					box-sizing: border-box;
					border-radius: 6rpx;

					&:first-child {
						margin-left: 0;
					}

					&:nth-of-type(2) {
						width: 226rpx;
					}

					&:nth-of-type(3) {
						width: 226rpx;
					}

					.icon-shijian {
						font-size: 24rpx;
					}

					.icon-ico_yuyueguanli_jiedaiyuyue {
						font-size: 26rpx;
					}
				}

				:deep(.u-input) {
					border: none !important;
				}
			}

			.tab_wrap {

				.tab_btn {
					width: 200rpx;
					height: 80rpx;
					margin-right: 20rpx;
					line-height: 80rpx;
					font-size: 28rpx;
					text-align: center;
					color: #fff;
					background-color: $act-color;
					border-radius: 6rpx;

					&.tab_act {
						background-color: $base-bg;
					}

				}
			}


			.deceased {
				padding: 60rpx 0 0 0;


				.deceased_item {
					margin-bottom: 20rpx;
					padding: 20rpx 0;
					color: $base-color;
					border-bottom: 1rpx solid $bor-color;

					.img {
						width: 120rpx;
						height: 120rpx;
						margin-left: 10rpx;
						border-radius: 50%;
					}

					.deceased_label {
						margin-left: 10rpx;
						text-align: center;
					}

					.deceased_btn_wrap {
						margin-left: auto;
						color: $act-color;

						.deceased_btn {
							margin-left: 20rpx;

							&:first-child {
								margin-left: 0;
							}
						}
					}
				}

			}
		}

		.savebtn {
			width: 90%;
			height: 80rpx;
			margin: 40rpx auto;
			line-height: 80rpx;
			font-size: 28rpx;
			text-align: center;
			color: #fff;
			background-color: $act-color;
			border-radius: 40rpx;
		}
	}
</style>